import * as React from 'react';
import { Props } from '../type';
import { GenerateUUID, GenerateUUID32 } from '@/utils';
import { moneyCapitalize } from '@/utils/utils';
import { connect } from 'react-redux';
import {
  getRelateProjectList,
  getProjectFeeRel,
  getAllowRucMatterList,
  GetProvideList,
  CostTypeInterface,
  getPaymentMethod
} from '@/services/laber-declare';
import { Toast } from 'antd-mobile-v2';
import _ from 'lodash';
import { getMatterStandardUnit } from '@/services/laber-declare';
import { clearRouteBlocker } from '@/components/form-group/route-blocker';
import { APPROVAL_STATUS } from '@/pages/declare/constants';
import { applyType } from '@/constants';
import { FormatDictData } from '@/utils/formatter';
import { ComponentType } from '@/plugins/form-render/constants/component-types';
interface ICostTypeItem {
  feeName: any;
  feeId: any;
  children?: Array<ICostTypeItem>;
}
interface MatterIdInfo {
  documentId: { text: string; value: string };
  documentName: string;
  documentCode: string;
  id: string;
  managerId: string;
  managerName: string;
  matterName: string;
  matterTotalUseAble: number;
  value: string;
  text: string;
  matterTotal?: number;
  orgName?: string;
}

interface CellProps {
  [propsname: string]: any;
}
export class GroupLaborStudentDeclare extends React.Component<Props, any> {
  matterIdList: MatterIdInfo[];
  projectList: any[];
  firstSet: number;
  provideItems: any;
  preProvideItems: any;
  constructor(props: Props) {
    super(props);
    this.firstSet = 1;
    this.preProvideItems = undefined;
    console.log('GroupLaborStudentDeclare props', props);
    this.state = {
      projectModalStatus: true,
      eventModalStatus: false,
      uuid: GenerateUUID(),
      newDataId: GenerateUUID32(),
      childrens: props.children,
      projectFeeRel: {
        applyType: applyType.STUDENT_LABOUR_APPLY,
        projectHeadNumber: '',
        projectTailNumber: '',
        userType: ''
      },
      matterStandardUnitList: [],
      payInfo: {}
      // provideItemAddList: []
    };
    getMatterStandardUnit().then((res) => {
      const { list: matterList } = FormatDictData(res.data, 'uint', 'meaning');
      console.log('===============matterList');
      console.log(matterList);

      this.setState({
        matterStandardUnitList: matterList
      });
    });
  }
  public static defaultProps = new Props();

  // 但官方并不推荐使用 UNSAFE_componentWillReceiveProps
  public UNSAFE_componentWillReceiveProps(newProps: any) {
    const { children } = this.props;
    if (children !== newProps.children) {
      this.setState({ childrens: newProps.children });
    }
  }

  componentDidMount() {
    if (this.props.form) {
      this.props.form.setSubmitCallback(this.saveData);
    }
    this.props.GaeaOnPropsCallback({
      relatedMattersAddList: {
        triScope: '1'
      },
      payId: {
        disabled: true,
        required: false,
        visibleConditions: [
          {
            componentType: ComponentType.RadioSelect,
            conditionValue: false
          }
        ]
      }
    });
    this.getProjectAttrOption();

    this.getProjectList();
    // this.getMatterIdList();
    setTimeout(async () => {
      let costTypeOption: Array<ICostTypeItem> = [];
      if (this.props.formValues?.projectId?.value) {
        const projectTailNumber = this.formatProjectId(
          this.props.formValues?.projectId
        );
        const projectFeeRel = {
          applyType: applyType.STUDENT_LABOUR_APPLY,
          projectTailNumber
        };
        costTypeOption = await this.getCostTypeList(projectFeeRel);
      } else {
        costTypeOption = await this.getCostTypeList(this.state.projectFeeRel);
      }

      //  编辑回显时根据费别设置二级费别
      const costType = this.props.formValues?.costType?.value;
      if (costType) {
        // // 自定义费别回显
        // {
        //   // const currentCostType = costTypeOption.filter((item: ICostTypeItem) => {
        //   //   return costType === item.feeId;
        //   // });

        //   // //  若费别不在请求的数组内 则代表为自定义费别
        //   // !currentCostType.length && this.setCostTypeList([{ feeId: costType, feeName: costType }, ...costTypeOption]);
        // }
        this.setSecondCostType(costType, true);
      }
    });
    this.getPaymentMethodList({ applyType: applyType.STUDENT_LABOUR_APPLY });
    const id = this.getSearchName('applyId');
    const status = Number(this.getSearchName('status'));
    if (id) {
      this.getProvideItem(id, status === 0 ? 2 : undefined);
    }
    // 监听对应内容变化，进行对应操作
    this.props.setChildHandlers &&
      this.props.setChildHandlers({
        onRelateProjectChange: this.onRelateProjectChange,
        onRelateEventChange: this.onRelateEventChange,
        onTotalAmountChange: this.onTotalAmountChange
      });
  }

  componentDidUpdate() {
    if (
      this.provideItems?.length > 0 &&
      !_.isEqual(this.preProvideItems, this.provideItems)
    ) {
      this.props.form?.setFieldsValue({
        provideItemAddList: this.provideItems
      });
      this.preProvideItems = this.provideItems;
    }
    if (
      this.matterIdList?.length > 0 &&
      this.projectList?.length > 0 &&
      this.firstSet == 1
    ) {
      if (this.props.formValues) {
        const matterId = this.props.formValues['matterId'];
        const matterInfo =
          this.matterIdList?.find(
            (item: any) => item.value === matterId?.value
          ) || ({} as MatterIdInfo);
        const projectId = this.props.formValues['projectId'];
        const projectInfo =
          this.projectList?.find(
            (item: any) => item.value === projectId?.value
          ) || {};
        const value =
          this.props.form?.getFieldValue('provideItemAddList') || [];

        // 重新提交需重新生成 dataId
        const status = Number(this.getSearchName('status'));
        if (status === APPROVAL_STATUS.Revert) {
          value.uuid = this.setUuid();
          this.props.form?.setFieldsValue({
            provideItemAddList: value
          });
        }

        this.firstSet++;
        this.setChildProps('provideItemAddList', {
          uuid: this.setUuid(),
          matterId: matterInfo.value, //关联事项id
          matterName: matterInfo.matterName, //关联事项名称
          matterTotal: matterInfo.matterTotal, //关联事项总金额
          matterTotalUseAble: matterInfo.matterTotalUseAble, //关联事项可用余额
          authorizeAmountUsable: projectInfo.descValue, //关联项目可用授权金额
          projectName: projectInfo.text
        });
        clearRouteBlocker();
      }
    }
  }

  getSearchName = (name) => {
    const locationStr = location.hash?.split('?')?.[1];
    const arr = locationStr?.split('&');
    const obj: any = {};
    for (let i = 0; i < arr?.length; i++) {
      const aItem = arr[i]?.split('=');
      obj[aItem[0]] = decodeURIComponent(aItem[1]);
    }
    return obj?.[name] || '';
  };

  // 获取关联项目列表
  getProjectList = async () => {
    const payload = {
      keyWord: '', // 搜索关键字
      lastId: '', // 最后一条数据主键
      pageNum: 1,
      pageSize: 200
    };
    this.setChildProps('projectId', {
      enableSearch: true,
      isDeclare: true,
      useExternal: true,
      externalOption: {
        url: '/ruProjectCode/api/v1/ruProjectCode/list',
        placeholder: '项目名称/编号/负责人',
        rows: true,
        searchData: {
          keyWord: '', // 搜索关键字
          lastId: '', // 最后一条数据主键
          pageNum: 1,
          pageSize: 50,
          totalIssued: 0
        },
        formatVal: {
          text: 'projectName',
          value: 'projectInnerCode',
          // descTitle: '可用授权金额：',
          // descValue: 'authorizeAmountUsable',
          descTitle: '部门名称：',
          descValue: 'orgName',
          disabled: 'projectBalance'
        }
      },
      // options: list,
      onChange: this.onProjectIdChange
    });
    const res = await getRelateProjectList(payload);
    const list = res.data.rows?.map((item: any) => {
      return {
        text: item.projectName,
        value: item.projectInnerCode,
        // descTitle: '可用授权金额：',
        // descValue: item.authorizeAmountUsable,
        descTitle: '部门名称：',
        descValue: item.orgName,
        disabled: item.projectBalance == 0 || item?.isDelete === 1,
        ...item
      };
    });
    this.projectList = list;
  };

  // 获取关联事项列表
  getMatterIdList = async () => {
    const payload = {
      keyWord: '', // 搜索关键字
      lastId: '', // 最后一条数据主键
      pageNum: 1,
      pageSize: 200
      // triScope: this.props.triScope
    };
    const res = await getAllowRucMatterList(payload);
    const list = res.data.rows.map((item: any) => {
      return {
        text: item.matterName,
        value: item.id,
        descTitle: '事项余额：',
        descValue: item.matterTotalUseAble,
        disabled:
          (!item.matterTotalUseAble || item.matterTotalUseAble === 0) &&
          item.matterTotalUseAble !== -1,
        ...item
      };
    });
    this.matterIdList = list;

    // this.setChildProps('matterId', {
    //   enableSearch: true,
    //   isDeclare: true,
    //   useExternal: true,
    //   externalOption: {
    //     url: '/api/rucMatter/v1/rucMatter/apply/list',
    //     placeholder: '事项名称/经办人',
    //     rows: true,
    //     searchData: {
    //       keyWord: '', // 搜索关键字
    //       lastId: '', // 最后一条数据主键
    //       pageNum: 1,
    //       pageSize: 50
    //     },
    //     formatVal: {
    //       text: 'matterName',
    //       value: 'id',
    //       descTitle: '事项余额：',
    //       descValue: 'matterTotalUseAble',
    //       disabled: 'matterTotalUseAble'
    //     }
    //   },
    //   // options: list,
    //   onChange: this.onMatterIdChange
    // });
  };

  formatProjectId = (val) => {
    const spcCode = val?.value.split('-')[1];
    let projectTailNumber = '';
    projectTailNumber = spcCode?.substr(-2, 2);
    return projectTailNumber;
  };
  // 监听项目属性变化
  onProjectAttrChange = (val: any) => {
    this.props.GaeaOnPropsCallback &&
      this.props.GaeaOnPropsCallback({
        relatedMattersAddList: {
          required: val.value !== 'ky'
        }
      });
  };
  // 写入项目属性
  getProjectAttrOption = () => {
    const options = [
      {
        text: '科研项目',
        value: 'ky'
      },
      {
        text: '非科研项目',
        value: 'fky'
      }
    ];
    this.setChildProps('projectAttr', {
      // onChange: this.onProjectAttrChange,
      disabled: true,
      placeholder: '根据关联项目自动填写'
    });
    this.props.GaeaOnPropsCallback &&
      this.props.GaeaOnPropsCallback({
        projectAttr: { options }
      });
  };

  // 获取费别列表
  // getCostTypeList = async (params: CostTypeInterface) => {
  //   console.log(params);

  //   const res = await getProjectFeeRel(params);
  //   const list = res.data?.feeList?.map(
  //     (item: { feeName: string; feeId: string }) => {
  //       return {
  //         text: item.feeName,
  //         value: item.feeId
  //       };
  //     }
  //   );
  //   //费别特殊处理，只有一个下拉选项默认选中
  //   if (list.length == 1) {
  //     this.props.form?.setFieldsValue({
  //       costType: list[0]
  //     });
  //   }
  //   this.setChildProps('costType', {
  //     options: list
  //     // placeholder: '请选择费别'
  //   });
  // };

  /**
   * 设置二级费别
   * @param value 一级费别的值
   * @param echoRender 是否为回显的时候设置 二级费别
   */
  setSecondCostType = (value: any, echoRender?: boolean) => {
    const currentCostType = this.state.costTypeMap?.get(value);
    const resetOption = !echoRender;
    if (currentCostType && currentCostType.children) {
      let options = currentCostType.children;
      const secondCostType = this.props.formValues?.secondCostType?.value;

      if (secondCostType && echoRender) {
        // 判断是否为自定义二级费别
        const currentSecondCostType = options.filter(
          (item: any) => item.value === secondCostType
        );
        !currentSecondCostType.length &&
          (options = [
            {
              value: secondCostType,
              text: secondCostType,
              key: secondCostType
            },
            ...options
          ]);
        if (options.length == 1) {
          const timer = setTimeout(() => {
            this.props.form?.setFieldsValue({
              secondCostType: options[0]
            });
            clearTimeout(timer);
          }, 300);
        } else {
          const timer = setTimeout(() => {
            this.props.form?.setFieldsValue({
              secondCostType: this.props.formValues?.secondCostType
            });
            clearTimeout(timer);
          }, 300);
        }
      }
      this.props.GaeaOnPropsCallback({
        secondCostType: {
          required: true,
          rules: [
            {
              validator: async (_: any, value: any) => {
                const patrn = /[$]/im;
                if (patrn.test(value.value)) {
                  // 如果包含特殊字符返回false
                  return Promise.reject(new Error('二级费别中不能含有$字符'));
                }
              }
            }
          ],
          customOption: true,
          options,
          resetOption,
          visibleConditions: [
            {
              componentType: ComponentType.RadioSelect,
              conditionName: 'costType',
              conditionValue: true
            }
          ]
        }
      });
    } else {
      this.props.GaeaOnPropsCallback({
        secondCostType: {
          required: false,
          rules: [],
          customOption: true,
          resetOption,
          visibleConditions: [
            {
              componentType: ComponentType.RadioSelect,
              conditionValue: false
            }
          ],
          options: []
        }
      });
      this.props.form?.setFieldsValue({
        secondCostType: undefined
      });
    }
  };

  // 监听费别变化
  onCostTypeChange = (val: any) => {
    if (val?.value) {
      this.props.form?.setFieldsValue({
        secondCostType: undefined
      });
      this.setSecondCostType(val?.value);
    }
  };
  formatCostTypeData = (data: Array<ICostTypeItem> = [], deep?: boolean) => {
    const map = new Map();
    const list: Array<any> = [];
    data?.forEach((item: ICostTypeItem) => {
      const { feeName: text, feeId: value, children } = item;
      if (deep) {
        if (text != '其他') {
          list.push({
            text,
            value
          });
        }
      } else {
        //  设置是否有children， 要隐藏列表二级列表里的其他选项，转换为自定义
        const secondCostType =
          children &&
          children.length &&
          children.findIndex((item: ICostTypeItem) => item.feeName == '其他') >
            -1
            ? this.formatCostTypeData(children, true).list
            : undefined;
        map.set(value, {
          text,
          value,
          children: secondCostType
        });
        list.push({
          text,
          value,
          children: secondCostType
        });
      }
    });
    return {
      list,
      map
    };
  };

  //获取费别
  getCostTypeList = async (params: CostTypeInterface) => {
    const res = await getProjectFeeRel(params);
    this.setCostTypeList(res.data.feeTreeList);
    return res.data.feeTreeList;
  };
  //设置费别数据源
  setCostTypeList = (feeList: Array<ICostTypeItem>) => {
    const { list: options, map } = this.formatCostTypeData(feeList);
    this.setState({
      costTypeMap: map
    });

    //费别特殊处理，只有一个下拉选项默认选中
    if (options.length == 1) {
      this.props.form?.setFieldsValue({
        costType: options[0]
      });
    }
    this.setChildProps('costType', {
      // customOption: true,
      options,
      onChange: this.onCostTypeChange
    });
  };

  // 获取支付方式列表
  getPaymentMethodList = async (params: { applyType: string }) => {
    const res = await getPaymentMethod(params);
    const list = res.data?.map((item: { payName: string; payCode: string }) => {
      return {
        text: item.payName,
        value: item.payCode
      };
    });
    //支付方式特殊处理，只有一个下拉选项默认选中
    if (list.length === 1) {
      this.props.form?.setFieldsValue({
        payId: list[0]
      });
      this.setState({
        payInfo: list[0]
      });
    }
    this.setChildProps('payId', {
      options: list
    });
  };

  // 获取申报发放明细表列表
  getProvideItem = async (id, source) => {
    const param = {
      reportId: id,
      source, // 1-导入 2-人工录入
      pageSize: 10,
      pageNum: 1
      // status: 0 // -1-无效 0-草稿 1-已提交
    };
    const res = await GetProvideList(param);
    if (res.data && res.data.total >= 0) {
      let amountAll = 0;
      res.data?.rows?.forEach((item: any) => {
        amountAll += item.provideAmount;
      });
      amountAll = parseFloat(amountAll.toFixed(2));
      const totalAmountText = moneyCapitalize(String(amountAll));
      this.props.form?.setFieldsValue({
        totalAmount: amountAll,
        totalAmountText: totalAmountText
      });
      const list = res.data?.rows;
      list?.forEach((item: any) => {
        const unit = this.state.matterStandardUnitList.filter(
          (unitI: any) => item.unit == unitI.value
        )?.[0];
        item.unit = {
          text: unit?.label,
          label: unit?.label,
          value: unit?.value
        };
        item.standard = {
          text: item.standardName,
          label: item.standardName,
          value: item.standardId,
          matterId: item?.matterId,
          matterName: item?.matterName
        };
        item.studentCode = {
          studentName: item.studentName,
          departmentName: item.departmentName,
          value: item.studentCode,
          text: `${item.studentName}/${item.studentCode}/${item.departmentName}`
        };
      });

      this.provideItems = list;
      const ids = list?.map((item: any) => item.id);
      this.setState({
        values: list,
        ids
      });
    }
  };

  // 发放总额
  onTotalAmountChange = (val: any) => {
    const totalAmountText = moneyCapitalize(String(val));
    this.props.form?.setFieldsValue({
      totalAmountText: totalAmountText
    });
  };

  //关联项目选择
  onProjectIdChange = (val) => {
    const { form } = this.props;
    const projectId = val;
    const projectInfo =
      this.projectList?.find((item: any) => item.value === projectId?.value) ||
      {};

    // form.setFieldsValue({
    //   // totalAmount: '',
    //   // totalAmountText: '',
    //   // provideItemAddList: []
    //   // costType: ''
    // });

    const { projectAttribute } = val;
    let projectAttr = {};
    if (projectAttribute) {
      projectAttr =
        projectAttribute == 1
          ? { text: '科研项目', value: 'ky' }
          : { text: '非科研项目', value: 'fky' };
      form.setFieldsValue({
        projectAttr
      });

      this.props?.GaeaOnPropsCallback({
        relatedMattersAddList: {
          required: Number(projectAttribute) !== 1
        }
      });
    }

    this.setChildProps('provideItemAddList', {
      uuid: this.setUuid(),
      authorizeAmountUsable: projectInfo.descValue, //关联项目可用授权金额
      projectName: projectInfo.text
    });

    const projectTailNumber = this.formatProjectId(val);
    this.setState(
      (prevState) => ({
        projectFeeRel: {
          ...prevState.projectFeeRel,
          applyType: applyType.STUDENT_LABOUR_APPLY,
          projectTailNumber
        }
      }),
      () => {
        // this.props.form?.resetFields('costType');
        // this.props.form?.setFieldsValue({ costType: undefined });
        this.getCostTypeList(this.state.projectFeeRel);
      }
    );
  };

  /**
   * 监听-明细内容变化
   * @param data 明细控件变动信息
   * @param data.values 变动信息Array
   * @param data.type 为变动类型（add新增 del删除 val内容）
   */

  //关联事项选择
  onMatterIdChange = (val: { value: string; text: string } | undefined) => {
    const { form } = this.props;
    const matterInfo =
      this.matterIdList?.find((item: any) => item.value === val?.value) ||
      ({} as MatterIdInfo);
    const projectId = form.getFieldValue('projectId');
    const projectInfo =
      this.projectList?.find((item: any) => item.value === projectId?.value) ||
      {};
    const documentIdText =
      (matterInfo.orgName || '') + (matterInfo.documentCode || '');
    form.setFieldsValue({
      documentId: { text: documentIdText, value: matterInfo.documentId },
      totalAmount: '',
      totalAmountText: '',
      provideItemAddList: []
    });
    this.setChildProps('provideItemAddList', {
      uuid: this.setUuid(),
      matterId: matterInfo.value, //关联事项id
      matterName: matterInfo.matterName, //关联事项名称
      matterTotal: matterInfo.matterTotal, //关联事项总金额
      matterTotalUseAble: matterInfo.matterTotalUseAble, //关联事项可用余额
      authorizeAmountUsable: projectInfo.descValue, //关联项目可用授权金额
      projectName: projectInfo.text
    });
  };

  // 通过路由信息获取是否在修改草稿/重新提交 页面
  isResubmit = () => {
    const pathname = location.href;
    const isEmitMode = pathname.indexOf('resubmit?') > -1;
    return isEmitMode;
  };

  setUuid = () => {
    const status = Number(this.getSearchName('status'));
    const dataId = this.getSearchName('applyId');
    const resubmit = this.getSearchName('resubmit');
    let uid = status !== APPROVAL_STATUS.Revert ? dataId : this.state.newDataId;
    if (resubmit === 'true' && status !== APPROVAL_STATUS.Draft) {
      uid = this.state.newDataId;
    }
    if (resubmit === '') {
      uid = this.state.newDataId;
    }
    return uid;
  };

  saveData = async () => {
    return new Promise((resolve, reject) => {
      const tmpFn = async () => {
        if (!this.props.form) {
          reject('form不存在');
        }
        // this.props.form.validateFields().catch();
        const values = await this.props.form
          .validateFields()
          .catch((err: any) => {
            if (err && err.errors) {
              const errorMsgList = [];
              for (const key in err.errors) {
                const errMsg = err.errors[key]?.errors?.[0].message;
                // Toast.fail(errMsg);
                errorMsgList.push(errMsg);
              }

              console.log(errorMsgList);
              const msgSortList = [
                'projectId',
                'projectAttr',
                'costType',
                'secondCostType',
                'contentAbstract'
              ];
              for (let i = 0; i < msgSortList.length; i++) {
                const key = msgSortList[i];
                if (err.errors[key]) {
                  const errMsg = err.errors[key]?.errors?.[0].message;
                  if (errMsg) {
                    Toast.fail(errMsg);
                    break;
                  }
                }
              }

              // errorMsgList.length && Toast.fail(errorMsgList[0]);
              reject(err);
            }
          });

        if (!values) return;

        const relatedMattersAddList = values.relatedMattersAddList?.value || [];
        let matterId = values.matterId || '';
        matterId = relatedMattersAddList.reduce(
          (prev: any, item: any, index: number) => {
            const id =
              index === relatedMattersAddList.length - 1
                ? item.id
                : item.id + ',';
            return prev + id;
          },
          ''
        );

        const matterNameStr = relatedMattersAddList.reduce(
          (prev: any, item: any, index: number) => {
            const matterName =
              index === relatedMattersAddList.length - 1
                ? item.matterName
                : item.matterName + ',';
            return prev + matterName;
          },
          ''
        );

        values.matterId = matterId || this.state.matterId;
        values.matterId = {
          text: matterNameStr,
          value: matterId || this.state.matterId
        };
        if (!values.documentId) {
          values.documentId = {
            text: relatedMattersAddList[0]?.documentName || '',
            value: relatedMattersAddList[0]?.documentId || ''
          };
        }

        // payCode: "3"
        // payName: "暂存"
        const { payInfo } = this.state;
        values.payId = {
          text: payInfo?.text || '暂存',
          value: payInfo?.value || '3'
        };

        const projectInfo =
          this.projectList?.find(
            (item: any) => item.value === values.projectId?.value
          ) || {};
        if (values.totalAmount > projectInfo.descValue) {
          Toast.fail(`${projectInfo.text}项目余额不足,请修改发放明细`);
          return;
        }
        const attachmentIds = values?.file?.map((item: any) => item.id);
        const extranalData = this.props?.form?.getFormExtranalData() || {};
        const { attachmentList } = extranalData;
        const importFileInfo = attachmentList
          ? attachmentList.find(
            (item: { fileType: number }) => item.fileType === 2
          )
          : null;
        const attachmentLists =
          attachmentIds?.map((item: any) => {
            return {
              fileType: 1,
              id: item
            };
          }) || [];
        const provideItemAddListObj = values?.provideItemAddList;
        const provideItemAddList = _.isArray(provideItemAddListObj)
          ? provideItemAddListObj
          : provideItemAddListObj?.list;
        // delReport: true->已删除明细附件, false-> 未删除明细附件
        if (!provideItemAddListObj?.delReport && importFileInfo) {
          attachmentLists.push({
            fileType: 2,
            id: importFileInfo?.id
          });
        }

        console.log(
          'provideItemAddList-----------------------[]',
          provideItemAddList
        );
        const provideItemParsed = provideItemAddList?.map((item: any) => {
          return {
            price: item.price,
            quantity: item.quantity,
            remark: item.remark,
            standardId: item.standard?.value,
            matterId: item.standard?.matterId || item?.matterId,
            matterName: item.standard?.matterName || item?.matterName,
            standardName: item.standard?.text?.split(' ')[0] || '自定义标准',
            studentCode: item.studentCode?.value,
            studentName: item.studentCode?.studentName,
            unit: item.unit?.value,
            startTime: item.startTime,
            endTime: item.endTime
            //typeof item.unit === 'number' ? item.unit : item.unit?.value
          };
        });
        const status = this.getSearchName('status');
        const dataId = this.getSearchName('applyId');
        // 重新提交需重新生成 dataId
        const oldDataId =
          this.isResubmit() && status === APPROVAL_STATUS.Revert
            ? {
              oldDataId: dataId
            }
            : {};
        if (values.provideItemAddList) {
          delete values.provideItemAddList;
        }
        resolve({
          result: true,
          data: {
            formValues: values,
            extra: {
              applyType: applyType.STUDENT_LABOUR_APPLY,
              dataId: this.setUuid(),
              applyName: decodeURIComponent(this.getSearchName('title')),
              extText: {
                orgId: this.getSearchName('orgId'), // history.getCurrentLocation().query.orgId,
                attachmentIds,
                provideItemAddList: provideItemParsed
                  ? JSON.stringify(provideItemParsed)
                  : ''
              },
              ...oldDataId
            }
          }
        });
      };
      tmpFn();
    });
  };

  onRelateProjectChange = () => {
    this.setState({
      projectModalStatus: true
    });
  };

  onRelateEventChange = () => {
    this.setState({
      eventModalStatus: true
    });
  };

  // receiveModalCallBack = (type: string, receiveObj) => {
  //   const {
  //     props: { form }
  //   } = this;
  //   const key = type === 'event' ? 'matterId' : 'projectId';
  //   form &&
  //     form.setFieldsValue({
  //       [key]: {}
  //     });
  // };
  /**
   * 根据code设置对应child的props，
   * @param code 对应控件code
   * @param cellProps props传参
   */
  public setChildProps = (code: string, cellProps: object) => {
    console.log('code------{}', code);
    this.props?.GaeaOnPropsCallback({
      [code]: {
        ...cellProps
      }
    });

    // 导致组件重复的渲染！！！
    // const { childrens } = this.state;
    // childrens.forEach((child: any) => {
    //   if (!child?.props?.viewport?.instances) return;
    //   child.props.viewport.instances.forEach((item: any) => {
    //     if (item.data.props.code === code) {
    //       item.data.props = { ...item.data.props, ...cellProps };
    //       return;
    //     }
    //   });
    // });
    // this.setState({ childrens, uuid: GenerateUUID() });
  };

  public render() {
    const { childrens, uuid } = this.state;
    return <div key={uuid}>{childrens}</div>;
  }
}

export default connect()(GroupLaborStudentDeclare);
// ({ capproval, loading }: ConnectState) => {
//   return {
//     // loading: loading.effects['capproval/startProcess'],
//   };
// }
